/**
 * 选择审核人
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Select } from 'antd';
import React, { useState, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';

import {
  getDeptUserInfo
} from '../service';

const { Option } = Select;

class PrivateData {
  static list = [];
  static paramsObj = {
    current: 1,
    pageSize: 10,
    roleName: ''
  };
}

const AuditPopup = props => {

  const { modalVisible, onCancel, onSubmit, roleName } = props;

  const [selectVal, setSelectVal] = useState([]);
  const [isMoreData, setIsMoreData] = useState(false); // 是否有更多数据
  const [selectOptionList, setSelectOptionList] = useState([]); // 审核人列表

  // 获取审核人列表
  const { run: runGetDeptUserInfo, loading } = useRequest(data => getDeptUserInfo(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '获取审核人列表');
      let arr = res.data || [];
      let _arr = [];
      for (let item of arr) {
        PrivateData.list.push({
          value: item.userId,
          label: item.userName
        });
      }

      // 是否有更多的数据
      if (arr.length >= PrivateData.paramsObj.pageSize) {
        setIsMoreData(true);
      } else {
        setIsMoreData(false);
      }

      setSelectOptionList([...PrivateData.list]);
    }
  });

  useEffect(() => {
    PrivateData.paramsObj.current = 1;
    PrivateData.paramsObj.roleName = roleName;
    if (modalVisible) {
      runGetDeptUserInfo(PrivateData.paramsObj);
    } else {
      PrivateData.paramsObj.current = 1;
      PrivateData.list = [];
    }
  }, [modalVisible, roleName]);

  // 选择
  const onChange = useCallback((val) => {
    setSelectVal(val);
  }, []);

  // 滚动
  const onPopupScroll = useCallback(e => {
    if (!isMoreData || loading) return;
    const { clientHeight, scrollHeight, scrollTop } = e.target;
    if (scrollTop >= scrollHeight - clientHeight) {
      PrivateData.paramsObj.current++;
      runGetDeptUserInfo(PrivateData.paramsObj);
    }
  }, [isMoreData, loading]);

  const okHandle = useCallback(() => {
    if (selectVal.length >= 1) onSubmit(selectVal);
  }, [selectVal]);

  return (
    <Modal
      destroyOnClose
      title="选择审核人"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
    >
      <Select
        mode="multiple"
        onPopupScroll={onPopupScroll}
        onChange={onChange}
        placeholder="请选择审核人"
        style={{ width: '100%' }}>
        {selectOptionList.map((item) => (
          <Option key={item.value}>{item.label}</Option>
        ))}
      </Select>
    </Modal>
  )
}

export default AuditPopup;
